package com.example.Utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonUtils {
    private static final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 序列化成String类型
     * @param value 要序列化的数据
     * @return
     */
    public static String Serialize(Object value) {
        try {
            return objectMapper.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error serializing object to JSON: " + e.getMessage(), e);
        }
    }

    /**
     * 反序列化成传入的类型
     * @param json 要反序列化的字符串
     * @param valueType 反序列化成的对象
     * @return <T>
     * @param <T> <T>
     */
    public static <T> T Deserialize(String json, Class<T> valueType) {
        try {
            return objectMapper.readValue(json, valueType);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("Error deserializing JSON to object: " + e.getMessage(), e);
        }
    }
}
